<template>
  <div :id="`echart-${id}`" style="width: 500px;height: 300px;">

  </div>
</template>

<script>
import * as echarts from 'echarts';
export default {
    props: {
        title: String,
        titleAlign: {
            type: String,
            default: 'left',
            validator: function(val){
                return ['left','center','right'].includes(val)
            }
        },
        data: {
            type: Array,
            required: true
        },
        type: {
            type: String,
            default: 'line',
            validator: function(val){
                return ['bar','line'].includes(val)
            }
        },
        smooth: {
            type: Boolean,
            default: false
        },
        background: {
            type: Boolean,
            default: false
        }
    },
    data(){
        return {
            id: 0
        }
    },
    created(){
        // this.id = Math.ceil(Math.random() * 100) + '-' + Date.now()
        this.id = this.initId(10)
    },
    computed: {
        xList(){
            return this.data.map(item=>{
                return item.title
            })
        },
        yList(){
            return this.data.map(item=>{
                return item.value
            })
        }
    },
    mounted(){
        let echart = echarts.init(document.getElementById(`echart-${this.id}`))

        let option = {
            title: {
                text: this.title,
                left: this.titleAlign
            },
            xAxis: {
                type: 'category',
                data: this.xList
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                data: this.yList,
                type: this.type,
                smooth: this.smooth,
                areaStyle: this.background ? {} : null
            }]
        }


        echart.setOption(option)
    },
    methods: {
        initId(len){
            let word = 'abcdefghijklmnopqrstuvwxyz1234567890'
            let arr = word.split('')
            let str = ''
            for(var i=0;i<len;i++){
                let n = Math.floor(Math.random() * 36)
                str += arr[n]
            }
            return str
        }
    }
}
</script>

<style>

</style>